package com.hft.web.controller;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.hft.biz.trans.UrlManager;
import com.hft.biz.Vo.UrlVo;

@Controller
public class UrlController {
    @Autowired
    UrlManager urlManager;

    @RequestMapping("/url/add")
    @ResponseBody
    public String addURL(String urlSource) {
        UrlVo urlVo = urlManager.insertUrl(urlSource);
        if (null == urlVo) {
            return "0|" + urlSource;
        } else {
            return "1|" + urlVo.getUrlShort();
        }
    }

    @RequestMapping("/url/all")
    public String listAll(ModelMap modelMap) {
        modelMap.put("urlVoList", urlManager.selectAll());
        return "biz/url/all";
    }

    @RequestMapping("/url/query")
    public String queryByPage(ModelMap modelMap, String startrow, String num) {
        if (StringUtils.isBlank(startrow) || !NumberUtils.isDigits(startrow)
            || StringUtils.isBlank(num) || !NumberUtils.isDigits(num)) {
            modelMap.put("urlVoList", null);
            return "biz/url/all";
        }
        modelMap.put("urlVoList",
            urlManager.selectByPage(null, Integer.parseInt(startrow), Integer.parseInt(num)));
        return "biz/url/all";
    }

    @RequestMapping("/index")
    public String indexPage() {
        return "index";
    }

    @RequestMapping("/{url}")
    public String redirect2SourceUrl(@PathVariable String url) {
        UrlVo urlVo = urlManager.selectUrlByShorturl(url);
        if (null == urlVo) {
            return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/index";
        } else {
            return UrlBasedViewResolver.REDIRECT_URL_PREFIX + urlVo.getUrlSource().trim();
        }
    }
}
